"""
feeds.py

Created by Mike Thorpe on 2009-07-25.
Copyright (c) 2009 Mike Thorpe. All rights reserved.
"""
import logging

from google.appengine.api import urlfetch
from google.appengine.ext import db

from xml.dom import minidom
from django.utils import simplejson as json

class FeedCache(db.Model):
  """
  RSS Feeds to cache
  """
  name = db.StringProperty(required=True)
  description = db.StringProperty(required=True)
  url = db.LinkProperty(required=True)

  def get_all_articles(self):
    q = FeedArticle.all()
    q.filter("feed =", self)
    return q
    
  def update_cache(self):
    error_msgs = []
    status_msgs = []
    new_items = 0
    
    if self.url:
      r = urlfetch.fetch(self.url)

      if r.status_code == 200:
        dom = minidom.parseString(r.content)

        for item in dom.getElementsByTagName('item'):
          try:
            title = item.getElementsByTagName('title')[0].firstChild.data
            pubDate = item.getElementsByTagName('dc:date')[0].firstChild.data

            link = "" # Link can be null, apparently.
            if item.getElementsByTagName('link')[0].firstChild:
              link = item.getElementsByTagName('link')[0].firstChild.data

            q = FeedArticle.all()
            q.filter("link = ", link)
            
            if q.count() == 0:
              new_items += 1
              
            item = FeedArticle(
                            key_name=link,
                            title=title,
                            pubDate=pubDate,
                            link=link,
                            feed=self
                    ).put()

          except IndexError, ValueError: 
            # Exceptions thrown from minidom parser.
            error_msgs.append("Failed Parsing feed XML.")

        # end for item
        status_msgs.append("Update Complete")

      else: # r.status_code == 200
        error_msgs.append("Failed to grab rss feed.")
    
      return { "new_items": new_items ,
               "status_msgs": status_msgs,
               "error_msgs": error_msgs }
             
class FeedArticle(db.Model):
  """
  Items found on the RSS Feed
  """
  feed = db.ReferenceProperty(FeedCache)
  link = db.LinkProperty(required=True)
  title = db.StringProperty()
  pubDate = db.StringProperty()
